var http    = require('http');
var express = require('express');
var app     = express();
var port    = '6767';
app.use("/", express.static(__dirname + '/is'));
app.use("/c", express.static(__dirname + '/c'));

// 创建服务端
var cApp = http.createServer(app).listen(port, function() {
	console.log('running at port ' + port);
});

// socket io
(function() {
// return;
var io       = require('socket.io')(cApp);
var iScreen  = io.of('iScreen-socket');
var iControl = io.of('iControl-socket');
var sStore   = {
	socket:    null,
	timestamp: ''
};

// screen show end
iScreen.on('connect', function(socket) {
	console.log('iScreen connect');

	// 1.绑定操作事件
	socket.on('screen.operate', function(data) {
		iControl.emit('screen.operate', data);
	});

	// 2.绑定屏幕断开事件
	socket.on('disconnect', function() {
		iScreen.emit('control.operate', {action: 'disconnect'});
	});
});

// mobile control end
iControl.on('connect', function(socket) {

	if(sStore.socket && sStore.socket.connected) {
		socket.emit('tips', 'Other people connected, please try later.');
		socket.disconnect();
		console.log('refuse');
		return;
	}else {
		sStore.socket    = socket;
		sStore.timestamp = new Date().getTime();

		console.log('control.connect');
		iScreen.emit('control.connected', {});
		socket.emit('control.connected', {});
	}

	// 2.绑定操作事件
	socket.on('control.operate', function(data) {
		iScreen.emit('control.operate', data);
	});

	// 3.绑定断开事件
	socket.on('disconnect', function() {
		iScreen.emit('control.disconnect', {});
	});
});

})();